package com.zny.sescore.shiro;

import com.alibaba.fastjson.JSON;
import com.zny.sescore.exception.MessageEnum;
import com.zny.sescore.model.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Shiro认证过滤器，处理未认证情况的响应
 *
 * @author zhangnayi
 * @date 2021-03-28 10:03
 */
@Slf4j
public class ShiroAuthFilter extends FormAuthenticationFilter {

    public ShiroAuthFilter() {
        super();
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        log.info("******* ShiroAuthFilter onAccessDenied url={} params={}", httpServletRequest.getRequestURL(), httpServletRequest.getHeader("Cookie"));
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        servletResponse.setHeader("Content-Type", "application/json;charset=UTF-8");
        servletResponse.getWriter().write(JSON.toJSONString(ApiResult.failed(MessageEnum.UNAUTHORIZED)));
        return Boolean.FALSE;
    }
}
